document.addEventListener('DOMContentLoaded', function() {
    // 加载订单商品
    loadOrderItems();
    
    // 设置提交订单按钮事件
    document.getElementById('placeOrderBtn').addEventListener('click', placeOrder);
    
    // 检查用户是否登录
    if (!checkLogin()) {
        alert('请先登录');
        window.location.href = 'login.html?returnUrl=checkout.html';
        return;
    }
    
    // 加载默认收货地址
    loadDefaultAddress();
});

// 加载订单商品
function loadOrderItems() {
    const cartItems = JSON.parse(localStorage.getItem('cart')) || [];
    const orderItemsContainer = document.getElementById('orderItems');
    const orderTotalPriceElement = document.getElementById('orderTotalPrice');
    
    orderItemsContainer.innerHTML = '';
    
    if (cartItems.length === 0) {
        orderItemsContainer.innerHTML = '<p class="empty-order">购物车中没有商品</p>';
        orderTotalPriceElement.textContent = '¥0.00';
        return;
    }
    
    let totalPrice = 0;
    
    cartItems.forEach(item => {
        const orderItemElement = document.createElement('div');
        orderItemElement.className = 'order-item';
        orderItemElement.innerHTML = `
            <div class="item-name">${item.name} × ${item.quantity}</div>
            <div class="item-price">¥${(item.price * item.quantity).toFixed(2)}</div>
        `;
        orderItemsContainer.appendChild(orderItemElement);
        
        totalPrice += item.price * item.quantity;
    });
    
    orderTotalPriceElement.textContent = `¥${totalPrice.toFixed(2)}`;
}

// 加载默认收货地址
function loadDefaultAddress() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (!currentUser) return;
    
    const addresses = JSON.parse(localStorage.getItem('addresses')) || [];
    const defaultAddress = addresses.find(addr => 
        addr.userId === currentUser.id && addr.isDefault
    );
    
    if (defaultAddress) {
        document.getElementById('name').value = defaultAddress.name;
        document.getElementById('phone').value = defaultAddress.phone;
        document.getElementById('address').value = `${defaultAddress.province} ${defaultAddress.city} ${defaultAddress.district} ${defaultAddress.detail}`;
    }
}

// 提交订单
function placeOrder() {
    const shippingForm = document.getElementById('shippingForm');
    const name = shippingForm.elements['name'].value.trim();
    const phone = shippingForm.elements['phone'].value.trim();
    const address = shippingForm.elements['address'].value.trim();
    const notes = shippingForm.elements['notes'].value.trim();
    
    // 表单验证
    if (!name || !phone || !address) {
        alert('请填写完整的收货信息');
        return;
    }
    
    if (!validatePhone(phone)) {
        alert('请输入有效的手机号码');
        return;
    }
    
    const cartItems = JSON.parse(localStorage.getItem('cart')) || [];
    if (cartItems.length === 0) {
        alert('购物车中没有商品');
        return;
    }
    
    const paymentMethod = document.querySelector('input[name="payment"]:checked').value;
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    
    // 创建订单
    const order = {
        id: Date.now(),
        userId: currentUser.id,
        date: new Date().toLocaleString(),
        items: cartItems,
        shippingInfo: { 
            name, 
            phone, 
            address,
            notes 
        },
        paymentMethod,
        total: cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0),
        status: 'pending' // 待付款
    };
    
    // 保存订单
    let orders = JSON.parse(localStorage.getItem('orders')) || [];
    orders.push(order);
    localStorage.setItem('orders', JSON.stringify(orders));
    
    // 清空购物车
    localStorage.removeItem('cart');
    updateCartCount();
    
    // 跳转到订单完成页
    window.location.href = `order-complete.html?id=${order.id}`;
}